package tom.reactor.websocket.handler;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;
import tom.reactor.model.User;
import tom.reactor.service.UserService;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Optional;

/**
 * 收到消息和发送消息
 * @author ZHUFEIFEI
 */
@Slf4j
@Component
public class UserHandler implements WebSocketHandler {

    @Autowired
    private UserService userService;

    private Map<String, User> users;

    @PostConstruct
    public void init() {
        users = Maps.newConcurrentMap();
        for (int i=0; i < 10; i++) {
            users.put("tom"+i, new User(Long.valueOf(i), "tom"+i));
        }
    }

    @Override
    public Mono<Void> handle(WebSocketSession session) {

        //map()方法 lambda参数不能为null
        return session.send(
                session.receive()
                .map(m -> Optional.ofNullable(this.users.get(m.getPayloadAsText())).orElse(new User()))
                .map(user -> session.textMessage(user.toString()))
        );
    }
}
